import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

import 'package:get/get.dart';

import 'package:package_info/package_info.dart';
import 'package:sp_util/sp_util.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';
import 'package:yp/util/util.dart';
import 'state.dart';


class LoginLogic extends GetxController {
  final state = LoginState();

  void onToggle() {
    state.showPassword.value = !state.showPassword.value;
  }

  @override
    void onInit() async {
      super.onInit();
      PackageInfo packageInfo = await PackageInfo.fromPlatform();
      state.version = packageInfo.version ?? "";
      state.buildNumber = packageInfo.buildNumber ?? "";
      var a =  SpUtil.getString('yes');
      if(a=='a'){
        state.show = false;
      }
      state.controller1.text = SpUtil.getString('number');
      update();

      fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
        if (res is fluwx.WeChatAuthResponse) {
          var params = {
            "appid": "wx74c3f1abaacda5dc",
            "code": res.code,
            'use_platform':20
          };
          Api.wxLogin(params).listen((event) {
            if(event["code"] != 0){
              if(event["code"] == -147213){
                // Get.toNamed(RouteConfig.bindPhone,arguments: event);
              }
            }else{
              SpUtil.putString('empeName', event["usr_name"]);
              SpUtil.putInt('empeNumId', event["usr_num_id"]);
              SpUtil.putString('token', event["access_token"]);
              SpUtil.putString('token', event["access_token"]);

              toast("登录成功");
              Get.offAllNamed(RouteConfig.main);
            }
          });
        }
      });
     
      update();
    }


  //请求发送验证码
  void sendSms(){
    var params = {
      "mobile":state.controller1.text,
      "verify_code_type": "login"
    };
    Api.sendSms(params).listen((event) {
      if(event['code'] == 0){
        toast("验证码已发送,请注意查收");
        state.smsData = event;
      }else{
        toast(event['message']);
      }

      update();
    });

    state.timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (state.seconds == 0) {
        state.timer?.cancel();
        state.verifyStr = '重新发送';
        state.seconds = 60;
        update();
        return;
      }
      state.seconds = --state.seconds;
      state.verifyStr = "已发送${state.seconds}s";
      print("已发送${state.seconds}s");
      update();
    });
  }

  void selectStatus(){
    print(5645644);
    state.status = !state.status;
    update();
  }

  /// 登录
  void onSubmit() {
    if(state.status==false){
      toast('请先阅读并同意勾选服务协议');
      return;
    }
    String email = state.controller1.text;
    String password = state.controller2.text;
    if (email.isEmpty || password.isEmpty) {
      toast("username and password can't be empty");
      return;
    }

    if(state.loginType != 1){
      var params = {
        "account": state.controller1.text,
        "password": state.controller2.text,
        'use_platform':20

      };
      Api.login(params).listen((event) {


        if(event["code"] != 0){
          toast(event["message"]);
        }else{
          // SpUtil.putString('sid', event["sid"]);
          // SpUtil.putString('salt', event["salt"]);
          SpUtil.putString('empeName', event["usr_name"]);
          SpUtil.putInt('empeNumId', event["usr_num_id"]);
          SpUtil.putString('userNumId', event["usr_num_id"].toString());
          SpUtil.putString('token', event["access_token"]);
          SpUtil.putString('number', state.controller1.text);
          toast("登录成功");
          Get.offAllNamed(RouteConfig.main);
        }
      });
    }else {
      var params = {
        "channel_num_id":99,
        "mobile": state.controller1.text,
        "sms_verify_code": state.controller2.text,
        "sms_verify_token": state.smsData["token"],
        "sms_verify_type": "login",
        'use_platform':20

    };
      Api.registMember(params).listen((event) {
        print("##########$event");
        if (event["code"] != 0) {
          toast(event["message"]);
        } else {
          SpUtil.putString('empeName', event["usr_name"]);
          SpUtil.putInt('empeNumId', event["usr_num_id"]);
          SpUtil.putString('userNumId', event["usr_num_id"].toString());
          SpUtil.putString('token', event["access_token"]);

          SpUtil.putString('number', state.controller1.text);
          toast("登录成功");
          Get.offAllNamed(RouteConfig.main);
        }
      });
    };
  }
  /// 调用sdk登录 确保签名一样 包名一样
  void wxLogin() {
    fluwx.sendWeChatAuth(scope: "snsapi_userinfo",state: 'wechat_sdk_demo_test',).then((data) {
      //监听微信授权返回结果
      print(">>>>>>>>！wechatLogin！>>>>>$data");
    }).catchError((e) {
      print('wxcodefalse $e');
    });
  }
  @override
  void onClose() {
    super.onClose();
    state.timer?.cancel();
  }


  void hide(){
    state.show = false;
    SpUtil.putString('yes', 'a');
    update();
  }

}
